package com.yupi.yupicturebackend.manager;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
@Component
public class FileManager {


    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    //上传图片
    public UploadPictureResult uploadPicture(MultipartFile multipartFile,String uploadPathPrefix) {
        //校验图片
        validPicture(multipartFile);
        //图片上传地址
        String uuid= RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        //自己拼接文件上传路径 而不是使用原始文件名称，可以保证安全性
        String uploadFileName=String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,originalFilename);
        String uploadFilePath=String.format("/%s/%s",uploadPathPrefix,uploadFileName);
        File file=null;
        
        //上传文件
        try {
            file=File.createTempFile(uploadFileName, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            //获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            //计算宽高
            int picWidth=imageInfo.getWidth();
            int picHeight=imageInfo.getHeight();
            double picScale=(double) picWidth/picHeight;

            //封装返回结果
            UploadPictureResult uploadPictureResult=new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+uploadFilePath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());

            //返回可访问的地址
            return uploadPictureResult;


        } catch (IOException e) {
            log.error("file upload error{}",uploadFilePath,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            //临时文件清理
            this.deleteTempFile( file);
        }



    }

    //上传图片 （URL）
    public UploadPictureResult uploadPictureUrl(String fileUrl,String uploadPathPrefix) {
        //校验图片
        validPicture(fileUrl);
        //图片上传地址
        String uuid= RandomUtil.randomString(16);
        String originalFilename = FileUtil.mainName(fileUrl);
        //自己拼接文件上传路径 而不是使用原始文件名称，可以保证安全性
        String uploadFileName=String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,FileUtil.getSuffix(originalFilename));
        String uploadFilePath=String.format("/%s/%s",uploadPathPrefix,uploadFileName);
        File file=null;

        //上传文件
        try {
            file=File.createTempFile(uploadFileName, null);
            HttpUtil.downloadFile(fileUrl,file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            //获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            //计算宽高
            int picWidth=imageInfo.getWidth();
            int picHeight=imageInfo.getHeight();
            double picScale=(double) picWidth/picHeight;

            //封装返回结果
            UploadPictureResult uploadPictureResult=new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+uploadFilePath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());

            //返回可访问的地址
            return uploadPictureResult;


        } catch (IOException e) {
            log.error("file upload error{}",uploadFilePath,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            //临时文件清理
            this.deleteTempFile( file);
        }



    }




    //   //校验图片
    private void validPicture(MultipartFile multipartFile) {

        ThrowUtils.throwIf(multipartFile==null, ErrorCode.PARAMS_ERROR, "上传图片不能为空");

        //校验文件大小
        long fileSize=multipartFile.getSize();
        final  long ONE_MB=1024*1024;
        ThrowUtils.throwIf(fileSize>2*ONE_MB,ErrorCode.PARAMS_ERROR,"上传图片大小不能超过2MB");
        //校验文件后缀
        String fileSuffix= FileUtil.getSuffix(multipartFile.getOriginalFilename());
        //允许上传的文件后缀列表
        final List<String> ALLOW_FORMAT_LIST= Arrays.asList("png","jpg","jpeg","gif","webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"上传图片格式错误");


    }


    //   //校验图片
    private void validPicture(String fileUrl) {

        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        try {
            //1，验证URL格式
            new URL(fileUrl); //验证是否是合法的URL格式
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        //2校验URL协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),ErrorCode.PARAMS_ERROR,
                "仅支持HTTP或HTTPS协议的文件地址");


        //3.发送HEAD请求以验证文件是否存在
        HttpResponse httpResponse = null;

        try {
            httpResponse=HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            //未正常返回 报异常
            if( httpResponse.getStatus()!=200){

                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件不存在");
            }

            //4.校验文件类型
            String contentType=httpResponse.header("Content-Type");
            if(StrUtil.isNotBlank(contentType)){
                //允许图片的类型
                //允许的文件形式
                final List<String> ALLOW_CONTENT_TYPES= Arrays.asList("image/png","image/jpg","image/jpeg","image/gif","image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType),ErrorCode.PARAMS_ERROR,"上传图片格式错误");
            }

            //5.校验文件大小
            String contentLengthStr=httpResponse.header("Content-Length");
            if(StrUtil.isNotBlank(contentLengthStr)){

                try {
                    long contentLength=Long.parseLong(contentLengthStr);
                    final  long TWO_MB=1024*1024*2;
                    ThrowUtils.throwIf(contentLength>TWO_MB,ErrorCode.PARAMS_ERROR,"上传图片大小不能超过2MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件大小格式错误");
                }
            }
        } finally {
            if(httpResponse != null){
                httpResponse.close();
            }
        }






    }

    //删除临时文件逻辑
    public void deleteTempFile(File file) {
        if (file == null){
            return;
        }
        //删除临时文件
        boolean delete = file.delete();
        if (!delete){
            log.error("file delete error{}",file.getAbsolutePath());
        }
    }



}
